<template>
  <div ref="chart" class="chart-1"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      m: null,
      o: {
        title: {
          text: "商家销售统计",
          left: 20,
          top: 25,
          textStyle: {
            color: "#fff",
            fontSize: 15,
            fontWeight: "bold"
          }
        },
        yAxis: {
          type: 'category',
          data: [],
          splitLine: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          }
        },
        xAxis: {
          type: 'value',
          splitLine: {
            show: false
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#fff'
            },
          }
        },
        series: {
          data: [],
          type: 'bar',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(84, 83, 238, 0.9)' // 0% 处的颜色
              }, {
                offset: 1, color: 'rgba(167, 109, 229, 0.9)' // 100% 处的颜色
              }],
              global: false // 缺省为 false
            },
            borderRadius: [0, 30, 30, 0], // 四个角的圆角半径
            borderWidth: 0 // 边框宽度
          },
          barWidth: '35%' // 控制柱子宽度
        }

      },
      ws: null,
      page: 1
    }
  },
  methods: {
    getData() {
      // ws 常连接(双向通信，实时性)
      //实例
      this.ws = new WebSocket("ws://127.0.0.1:9998")
      //连接
      this.ws.onopen = () => {
        console.log("连接成功");
        //连接成功之后发送数据
        let params = {
          action: 'getData',
          socketType: 'sellerData',
          chartName: 'seller',
          value: ''
        }
        //发送
        this.ws.send(JSON.stringify(params))

        //接收数据
        this.ws.onmessage = (e) => {
          // console.log(e.data);

          //原始数据
          let data = JSON.parse(e.data)
          // console.log(data.data);

          //需要的数据
          let sellers = JSON.parse(data.data)
          //总条数
          let total = Math.ceil(sellers.length / 5)
          //数组排序(从大到小)
          sellers.sort((a, b) => b.value - a.value)
          //相当于做分页
          let list = sellers.slice((this.page - 1) * 5, this.page * 5)

          //用数据修改option
          this.o.yAxis.data = list.map(item => item.name).sort((a, b) => a - b)
          this.o.series.data = list.map(item => item.value).sort((a, b) => a - b)
          //用新数据渲染
          this.m.setOption(this.o)

          //页数增肌
          this.page++

          //判断是否还有数据
          if (this.page > total) {
            this.page = 1
          }
        }
      }

    }
  },
  mounted() {
    //实例
    this.m = echarts.init(this.$refs.chart)
    //用数据渲染
    this.getData()
  }
}
</script>

<style scoped>
.chart-1 {
  height: 100%;
}
</style>